﻿using System;
using EnvDTE;
using EnvDTE80;
using VSLangProj;
using System.Runtime.Serialization;
using Microsoft.Practices.RecipeFramework;
using System.Xml;
using System.IO;

namespace SMC.SPALM.References
{
    [Serializable]
    public class AddFeaturesReference : UnboundRecipeReference
    {
        public AddFeaturesReference( string recipe ) : base( recipe )
        {
        }

        protected AddFeaturesReference(SerializationInfo info, StreamingContext context ) : base( info, context )
        {
        }

        public override bool IsEnabledFor( object target )
        {
            if( target is ProjectItem)
            {
                if (((ProjectItem)target).Name.ToUpper().EndsWith(".XML"))
                {
                    try
                    {
                        string itempath = ((ProjectItem)target).Properties.Item("FullPath").Value.ToString();
                        if (File.Exists(itempath))
                        {
                            XmlDocument elementsFile = new XmlDocument();
                            elementsFile.Load(itempath);

                            XmlNamespaceManager nsmgr = new XmlNamespaceManager(elementsFile.NameTable);
                            nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");

                            XmlNode node = elementsFile.SelectSingleNode("/ns:Elements", nsmgr);
                            if (node != null)
                            {
                                //file contains <elements> tag
                                return true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return false;
         }
        
        public override string AppliesTo
        {
             get
             {
                 return "Xml files containing an <elements> tag";
             }
        }
    }
}
